home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9284 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How do I write gets() function that checks for boundaries?
  5. Date: 8 Mar 1996 15:40:28 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4hqghcINNeh7@keats.ugrad.cs.ubc.ca>
  8. References: <313FDB9F.7455@cyberus.ca>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <313FDB9F.7455@cyberus.ca>, MC  <mcardinal@cyberus.ca> wrote:
  12. >I want to write my own gets() function that will check string size so that it doesn't accept more 
  13. >characters than my declared string variable.  Any ideas?
  14.  
  15. This feature is already implemented in fgets(). However, you want to know how
  16. it is done.
  17.  
  18. Well, you simply read characters into the given buffer and keep advancing the
  19. pointer. If you have done this n-1 times, where n is the input parameter
  20. specifying the buffer size, or you have run out of input (EOF condition, or
  21. newline character encountered), you bail out of the loop.  You affix a null
  22. character and you are done! Whether or not you choose to make the newline a
  23. part of the string is up to you, of course.
  24.  
  25. A more interesting question might be, "how do I write a gets() function (call
  26. it vgets() for ``variable'') that accepts _aribitrary_ input without
  27. overflowing?"
  28.  
  29. This you could do by using malloc() to allocate a buffer internal to vgets().
  30. You read into that buffer. When you have filled it up, you use realloc() to
  31. increase the size of the buffer as many times as you need to to read the whole
  32. line of text.
  33.  
  34. When you are done, you can use realloc() one more time to trim down the space
  35. to what is actually consumed by the line. With this technique, you can handle
  36. files that have lines of arbitrary length.
  37.  
  38. One of my pet peeves is text editor programs that limit the line length. The
  39. one I'm using right now, Vim, will let you load just about _anything_. I can
  40. pop a UNIX kernel into it, edit some strings, write it back and reboot.
  41. -- 
  42.  
  43.